package com.leen.admin.service.impl;


import com.leen.admin.dto.JobDTO;
import com.leen.admin.entity.Job;
import com.leen.admin.repository.JobRepository;
import com.leen.admin.service.Jobservice;
import com.leen.common.vo.ResponseVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;


@Transactional(rollbackFor = Exception.class)
@Service
public class JobserviceImpl extends CurdServiceImpl<Job,Long> implements Jobservice {
    private JobRepository jobRepository;

    @Autowired
    public void setJobRepository(JobRepository jobRepository){
        this.jobRepository=jobRepository;
        //给父类供职
        super.setCrudRepository(jobRepository);
    }

    @Override
    public ResponseVO search(JobDTO jobDTO) {
        //分页页码
        Pageable pageable = PageRequest.of(jobDTO.getPageNumber() - 1, jobDTO.getPageSize());
        //构建查询对象
        Specification<Job> specification = new Specification<Job>() {
            @Override
            public Predicate toPredicate(Root<Job> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List<Predicate> arr = new ArrayList<>();
                arr.add(criteriaBuilder.equal(root.get("name"), jobDTO.getName()));
                arr.add(criteriaBuilder.equal(root.get("enabled"), jobDTO.getEnabled()));
                //起始日期
                if (jobDTO.getStartTime()!=null && jobDTO.getStartTime().equals("")){
                    arr.add(criteriaBuilder.greaterThanOrEqualTo(root.get("createTime"),jobDTO.getStartTime()));
                }
                //结束日期
                if (jobDTO.getEndTime()!=null && jobDTO.getEnabled().equals("")){
                    arr.add(criteriaBuilder.lessThanOrEqualTo(root.get("createTime"),jobDTO.getEndTime()));
                }
                return criteriaBuilder.and(arr.toArray(new Predicate[arr.size()]));
            }
        };

        //查询
        Page<Job> page = this.jobRepository.findAll(specification, pageable);
        return new ResponseVO(page.getTotalElements(), page.getContent());
    }

}
